<template>
    <div class="order-item-container">
        <div class="row1">
            <div>{{ info.orderNumber }}</div>
            <div class="status" v-if="info.orderStatus == 1">待支付</div>
            <div class="status"
                v-if="new Date().getTime() > parseInt(info?.payTime + 10 * 60 * 1000) && info.orderStatus == 1">已超时
            </div>
            <div class="status" v-if="info.orderStatus == 2">已支付</div>
            <div class="status" v-if="info.orderStatus == 3">出票中</div>

            <div class="status" v-if="info.orderStatus == 10">已完成</div>


        </div>
        <nut-divider style="color: #eee;" />
        <div class="row2">
            <div class="image">
                <image src="http://supportmaster.liangpiao.net.cn/chuanshuo.jpg" style="width: 80px;border-radius: 5px;"
                    mode="widthFix">
                </image>
            </div>
            <div class="right">
                <div class="title">电影《传说》专属·全国通兑券</div>
                <div class="phone">{{ info.phone }}</div>

                <div class="row-price">
                    <div style="margin-left: 20px;">全国通兑券 * {{ info.productCount }}</div>
                    <div style="color: #ee0a24;">￥{{ (info.orderPrice / 100).toFixed(2) }}</div>
                </div>

            </div>
        </div>
        <nut-divider style="color: #eee;" />
        <div class="row3" v-if="info.orderStatus == 1">
            <div v-if="new Date().getTime() <= parseInt(info?.payTime + 10 * 60 * 1000)">
                <nut-countdown :startTime="new Date().getTime()" :endTime="parseInt(info?.payTime) + 10 * 60 * 1000"
                    @on-end="TimerOver(info)" style="color: #ee0a24;font-size: 12px;;"></nut-countdown>

            </div>
            <div v-else>已超时</div>

            <div v-if="new Date().getTime() <= parseInt(info?.payTime + 10 * 60 * 1000)">
                <nut-button size="mini" type="primary" @click="onClickPay">去支付</nut-button>
            </div>

            <div v-else></div>



        </div>
        <div class="row3" v-if="info.orderStatus == 2">
            <div></div>
            <div>
                等待出票码...

            </div>
        </div>
        <div class="row3" v-if="info.orderStatus == 3">
            <div></div>
            <div>
                等待出票码...

            </div>
        </div>
        <div class="row3" v-if="info.orderStatus == 10">
            <div></div>
            <div>
                <nut-button size="mini" type="primary" @click="onLook">查看券码</nut-button>

            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, toRefs, onMounted } from 'vue'
import { storeToRefs } from "pinia";
import { useUserStore } from "../../store";
import Taro from '@tarojs/taro';
const userStore = useUserStore();
import * as indexApi from '../../api/index'
const { Userinfo, shareUserId, Token, openid } = storeToRefs(userStore);

const props = defineProps({
    info: Object
})
const { info } = toRefs(props)
onMounted(() => {
})
const TimerOver = (e) => {
    // console.log("时间结束");
    // console.log(e, "----------------");
    e.orderStatus = -1;
};

const onLook = async () => {
    Taro.navigateTo({
        url: `/pages/detail/index?id=${info.value.id}`
    })
}
//立即支付
const onClickPay = async () => {
    try {

        const payData1 = await pollOrderResult(info.value.id, 10, 500);
        console.log(payData1, "payData1payData1");
        Taro.requestPayment({
            timeStamp: payData1.timeStamp,
            nonceStr: payData1.nonceStr,
            package: payData1.packageStr,
            signType: payData1.signType,
            paySign: payData1.paySign,
            success: function (res) {
                Taro.showToast({
                    title: "支付成功",
                    icon: "success",
                });
                Taro.redirectTo({
                    url: "/pages/order/index",
                });
            },

            fail: function (res) {
                Taro.showToast({
                    title: "支付失败",
                    icon: "error",
                });
                // setTimeout(() => {
                // Taro.redirectTo({
                //     url: "/pages/home/index",
                // });
                // }, 1000)

            },
        });

    } catch (error) {
        Taro.showToast({
            title: "网络错误",
            icon: "error"
        })
    }
};

const getPayData = async (orderId) => {
    const orderResult = await indexApi.submitOrderResult({ orderId });
    if (orderResult.state == 200 && orderResult.code == 200) {
        return orderResult; // 返回订单结果
    }
};

const pollOrderResult = async (orderId, maxTries, delay) => {
    if (maxTries <= 0) {
        // 达到最大尝试次数，停止轮询
        console.error("达到最大尝试次数，未获取到订单结果");
        return null; // 返回 null 或抛出错误表示失败
    }

    try {
        // 调用接口获取订单结果
        const orderResult = await indexApi.submitOrderResult({ orderId });

        // 检查订单结果是否满足条件
        if (orderResult.state == 200) {
            switch (orderResult.code) {
                case 200:
                    // 订单已处理完成，停止轮询
                    console.log("订单处理完成", orderResult);
                    Taro.hideLoading();
                    return orderResult.data; // 返回订单结果
                case 202:
                    // 订单仍在处理中（可能是一个特殊的成功状态码）
                    console.log("订单仍在处理中（202），稍后重试...");
                    // 注意：这里你可能不需要返回，因为不是错误，但也不是完成
                    // 如果想继续轮询，则不要返回，让函数继续执行
                    Taro.hideLoading();

                    break;
                case 503:
                    // 服务器内部错误
                    console.error("服务器内部错误，稍后重试...");
                    // 你可以选择在这里继续轮询，或者返回错误
                    // 如果选择继续轮询，则不要返回
                    break;
                default:
                    // 其他未知的错误码
                    console.error("未知的订单结果错误码", orderResult.code);
                    // 你可以在这里决定是继续轮询还是返回错误
                    break;
            }
        } else {
            // HTTP状态码不是200，通常表示有错误发生
            console.error("HTTP状态码错误", orderResult.state);
            // 在这里你可以选择继续轮询，返回null，或者抛出错误
        }

        // 如果未达到终止条件，则等待一段时间后再次尝试
        console.log("订单仍在处理中，稍后重试...");
        await new Promise((resolve) => setTimeout(resolve, delay));

        // 递归调用自己进行下一轮轮询
        return await pollOrderResult(orderId, maxTries - 1, delay);
    } catch (error) {
        // 处理获取订单结果时出现的错误
        // 可以选择重试、记录错误或停止轮询等
        console.error("获取订单结果时出错", error);

        // 如果错误允许重试，并且还有剩余尝试次数，则递归调用自己
        if (maxTries > 1) {
            return await pollOrderResult(orderId, maxTries - 1, delay);
        } else {
            // 如果没有剩余尝试次数，则返回null或抛出错误
            return null; // 或者抛出错误
        }
    }
};

</script>
<style lang="less">
.order-item-container {
    background-color: #fff;
    padding: 25px;
    border-radius: 12px;

    .row1 {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 24px;

        .status {
            color: #858a99;
        }
    }

    .row3 {
        font-size: 24px;
        color: #858a99;
        display: flex;
        justify-content: space-between;
    }

    .row2 {
        display: flex;
        // justify-content: space-between;
        margin-top: 30px;

        .image {}

        .right {
            flex: 1;
            margin-left: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-between;

            .title {
                font-size: 24px;
                font-weight: 700;
            }

            .phone {
                font-size: 24px;
                font-weight: 700;
            }

            .row-price {
                display: flex;
                width: 100%;
                justify-content: space-between;
                // align-items: center;
                font-size: 24px;
            }
        }

    }
}
</style>